﻿using Newtonsoft.Json;
using System.Collections.Generic;
using Telepathy.NetworkBase;
using Telepathy.Protocols;
using UnityEngine;
using UnityEngine.Events;

namespace Telepathy.Clients
{
    public class ClientManager : BaseTcp
    {
        private void Start()
        {
            InvokeRepeating("ConnectedInterval", 0, connectInterval); //发送心跳
        }

        #region 其他消息接收
        protected override void OnConnected(Message msg)
        {
            Debug.LogWarning(string.Format("客户端启动! id:{0}", msg.connectionId));
        }

        protected override void OnDisconnected(Message msg)
        {
            Debug.LogWarning(string.Format("断开链接! id:{0}", msg.connectionId));
        }
        protected override void OnLoginMessage(int connID, Protocols.LoginMessage msg)
        {
            base.OnLoginMessage(connID, msg);
            Dictionary<string, string> keyValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(msg.MsgBase.text);
            foreach (var item in keyValues)
            {
                Debug.LogWarning(string.Format("{0} - {1}", item.Key, item.Value));
            }
        }

        protected override void OnHeardMessage(int connID, Protocols.HeartMessage msg)
        {
            base.OnHeardMessage(connID, msg);
            Debug.LogWarning("收到服务器返回的心跳消息:{0}"+msg.MsgBase.text);
        }
        #endregion

        protected override void OnRecvMessage(int connID, Telepathy.Protocols.MyMessage msg)
        {
            Debug.LogWarning(string.Format("收到来自 {0} 服务端消息:{1}", connID, msg.MsgBase.text));

        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="strMsg"></param>
        /// <param name="headerType"></param>
        /// <returns></returns>
        public bool SendMsg(string strMsg, HeaderType headerType = HeaderType.Content, byte[] bytes = null)
        {
            MessageBase myMsg = GetMessageBase(strMsg, bytes, headerType);
            myMsg.messageId = MsgStringId;
            return SendToserver(myMsg.Serialize());
        }

        #region 心跳
        /// <summary>
        /// 设置重连次数
        /// </summary>
        [Space(10)] public int reConnCount = 1000;
        /// <summary>
        /// 链接间隔时间
        /// </summary>
        float connectInterval = 1f;

        /// <summary>
        /// 链接次数
        /// </summary>
        int connectCount = 0;

        public UnityAction<int> OnConnInterval = null;

        /// <summary>
        /// 心跳检查 断开重连 在Update中调用才有效
        /// </summary>
        protected void ConnectedInterval()
        {
            if (client == null || client.Connected == false)
            {
                Destroy();
                if (connectCount < reConnCount)
                {
                    //链接次数增加
                    connectCount++;
                    string str = string.Format("这是第{0}次 连接", connectCount);
                    Debug.Log(str);
                    StartClient(this.Ip, this.Port);  //重连一次
					if(client!=null) client.MaxMessageSize = 1024 * 1024;
                }
                OnConnInterval?.Invoke(connectCount);
            }
            else if (client.Connected)
            {
                SendMsg("1", HeaderType.Heart);
            }
        }
        #endregion
    }
}